package net.atomarrow.util;

import java.util.ArrayList;
import java.util.List;

import net.atomarrow.annotation.Priority;

public class PriorityUtil {

	public static List sort(List list){
		List list2=new ArrayList();
    	for(Object obj:list){
    		int priorityValue=getPriorityValue(obj);
    		if(priorityValue==0){
    			list2.add(obj);
			}else{
				insertTo(priorityValue,obj,list2);
			}
    	}
    	return list2;
	}
	 private static int getPriorityValue(Object controllerInterceptor){
	    	Priority priority;
	    	if(controllerInterceptor.getClass().isAnnotationPresent(Priority.class)){
				priority=controllerInterceptor.getClass().getAnnotation(Priority.class);
				int p=priority.value();
				return p;
			}else{
				return 0;
			}
	    }

		private static void insertTo(int p,Object ci, List newCis) {
			if(newCis.isEmpty()){
				newCis.add(ci);
				return;
			}
			Object newci;
			boolean insert=false;
			for(int i=0;i<newCis.size();i++){
				newci=newCis.get(i);
				int priorityValue=getPriorityValue(newci);
				if(priorityValue==0){
					newCis.add(i, ci);
					insert=true;
					break;
				}else{
					if(p<priorityValue){
						newCis.add(i,ci);
						insert=true;
						break;
					}
				}
			}
			if(insert==false){
				newCis.add(ci);
			}
		}
	
}
